
import { ref } from "vue"
import store from "@/store"
import { RouteRecordRaw } from "vue-router"
import { defineStore } from "pinia"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"
import { getToken, setToken, removeToken } from "@/utils/cache/cookies"
import { setUserInfo, getUserInfo, getUserId, setUserId } from "@/utils/cache/localStorage"
import { type ILoginRequestData, UserInfoResponseData, IApiResponseUserRoles } from "@/api/login/types/login"
import { loginApi, getUserInfoApi, getUserRolesApi } from "@/api/login"
import router, { resetRouter } from "@/router"


export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<IApiResponseUserRoles[] |  RouteRecordRaw[]>([])
  const userInfo = ref<UserInfoResponseData['data'] | null>(getUserInfo() as UserInfoResponseData['data'] | null)
  const u_id = ref<string>(getUserId() || '')
  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()
  /** 设置角色数组 */
  const setRoles = (value: IApiResponseUserRoles[] | RouteRecordRaw[]) => {
    roles.value = value
  }

  // 登录
  const login = (loginData: ILoginRequestData) => {
    return new Promise((resolve, reject) => {
      loginApi({
        username: loginData.username,
        password: loginData.password,
        type: loginData.type
      })
        .then((res) => {
          let rel = res.data
          setToken(rel.token)
          token.value = rel.token
          u_id.value = rel.u_id
          setUserId(rel.u_id)
          resolve(rel)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // 获取用户详情
  const getInfo = () => {
    return new Promise((resolve, reject) => {
      getUserInfoApi({ u_id: u_id.value })
        .then((res) => {

          let data = res.data
          userInfo.value = data;
          u_id.value = data.u_id;
          setUserInfo(JSON.stringify(data))
          setUserId(data.u_id)

          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  }
  // 获取用户权限
  const getUserRoles = () => {
    return new Promise((resolve, reject) => {
      getUserRolesApi({ u_id: u_id.value })
        .then((res) => {
          let data = res.data
          if(data && data.length > 0 ){
            setRoles(data)
            roles.value = data
            resolve(data)
          }else {
            // roles.value = asyncRouteSettings.defaultRoles
          }
          // 验证返回的 roles 是否是一个非空数组
          //   if (data.roles && data.roles.length > 0) {
          //     roles.value = data.roles
          //   } else {
          //     // 塞入一个没有任何作用的默认角色，不然路由守卫逻辑会无限循环
          //     roles.value = asyncRouteSettings.defaultRoles
          //   }
        }).catch((error) => {
          reject(error)
        })
    })
  }
  // 登出
  const logout = () => {
    removeToken()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 visited views 和 cached views */
  const _resetTagsView = () => {
  }

  return { token, roles, userInfo, setRoles, login, getInfo, getUserRoles, logout, resetToken }
})




/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
